package com.example.note.db;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.note.bean.Notepad;

import java.util.ArrayList;
import java.util.List;

public class NoteDbHelper extends SQLiteOpenHelper{
    public NoteDbHelper(@Nullable Context context) {
        super(context, "note.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    String sql = "create table notepad(id integer primary key autoincrement,content text,time text)";
    db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void insert(Notepad np){
        String sql = "insert into notepad(content,time) values(?,?)";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql,new Object[]{np.getContent(),np.getTime()});
        db.close();
    }

    public List<Notepad> FindNotes(){
        String sql = "select * from notepad";
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(sql,null);
        List<Notepad> list = new ArrayList<>();
        while (cursor.moveToNext()){
            Notepad np = new Notepad();
            np.setId(cursor.getInt(0));
            np.setContent(cursor.getString(1));
            np.setTime(cursor.getString(2));
            list.add(np);
        }
        cursor.close();
        return list;
    }
    public String FindContent(int id){
        String sql = "select content from notepad where id = ?";
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery(sql,new String[]{String.valueOf(id)});
        String content = "";
        while (cursor.moveToNext()){
            content = cursor.getString(0);
        }
        cursor.close();
        return content;
    }
    public void deletenotepad(Notepad np) {
        String sql = "delete from notepad where id = ?";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql,new Object[]{np.getId()});
    }

    public void updateNotepad(Notepad np, int id) {
        String sql = "update notepad set content = ? , time = ? where id = ?";
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(sql,new Object[]{np.getContent(),np.getTime(),id});
    }
}
